<?php

namespace app\controller\admin\mini;


use app\model\api\Mini;
use app\model\api\MiniAttire;
use app\model\api\MiniCrop;
use app\model\api\MiniImg;
use app\model\api\MiniMount;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Crop
 * @package app\controller\admin\mini
 */
class Mount extends Backend
{
    /**
     * api_log模型对象
     * @var \app\model\api\Log
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法
    public $orderRule = ['id' => 'desc'];

    public function _initialize()
    {
        $this->model = new MiniMount();
    }

    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data  = $this->model->alias('mo')->join('mini_record m','mo.record_id=m.id')->field(
                'mo.id,get_way,img,jump_height,life,p_id,price,skill,speed,type,m.name'
            )->where($where)->order($order)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->alias('mo')->join('mini_record m','mo.record_id=m.id')->field(
                'record_id as id,get_way,img,jump_height,life,p_id,price,skill,speed,type,m.name'
            )->where($where)->order($order)->paginate($limit)->toArray();
        }
        return $this->success('数据获取成功', $data);
    }

    public function miniImg()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $data = (new MiniImg())->order($order)->cache(true)->select()->toArray();
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        Db::startTrans();
        $post=CommonFun::filterPostData($this->request->post());
        $miniImg = (new MiniImg())->column('img','name');
        $record_insData['primary_type']='坐骑';
        $record_insData['second_type']='坐骑';
        $record_insData['name']=$post['name'];
        $record_insData['img_url']=$post['img'];
        if ($post['type']=='初阶'){
            $record_insData['if_show']=1;
        }else{
            $record_insData['if_show']=0;
        }
        $save_record=(new Mini())->insert($record_insData);
        $record_id = (new Mini())->getLastInsID();
        if (!$save_record) throw new \Exception('保存基本信息失败');
        $insData['img'] = $post['img'];
        $insData['record_id']  = $record_id;
        if ($post['type']=='初阶'){
            $insData['p_id']  = 0;
        }else{
            $insData['p_id']=$post['chujie'];
        }
        $insData['get_way'] = $post['get_way'];
        $insData['type'] = $post['type'];
        $insData['life'] = $post['life'];
        $insData['speed'] = $post['speed'];
        $insData['jump_height'] = $post['jump_height'];
        $insData['price'] = $post['price'];
        $skill = [];
        if(!empty($post['skill1_name'])){
            $skill[]=array(
                'img'=>$post['skill1_img'],
                'name'=>$post['skill1_name'],
                'describe'=>$post['skill1_describe'],
            );
        }
        if(!empty($post['skill2_name'])) {
            $skill[] = array(
                'img' => !empty($post['skill2_img']) ? $post['skill2_img'] : '',
                'name' => !empty($post['skill2_name']) ? $post['skill2_name'] : '',
                'describe' => !empty($post['skill2_describe']) ? $post['skill2_describe'] : '',
            );
        }
        if(!empty($post['skill3_name'])) {
            $skill[] = array(
                'img' => !empty($post['skill3_img']) ? $post['skill3_img'] : '',
                'name' => !empty($post['skill3_name']) ? $post['skill3_name'] : '',
                'describe' => !empty($post['skill3_describe']) ? $post['skill3_describe'] : '',
            );
        }
        $insData['skill']= json_encode($skill,JSON_UNESCAPED_UNICODE);
        try {
            $save = $this->model->save($insData);
            if (!$save) throw new \Exception('保存失败');
            Db::commit();
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function info(){
        $id = $this->request->param('id');
        $mount = $this->model->where('record_id',$id)->find()->toArray();
        $record_info  = (new Mini())->detail($id);
        $mount['name'] = !empty($record_info['name'])?$record_info['name']:'';
        $mount['second_type'] = !empty($record_info['second_type'])?$record_info['second_type']:'';
        $mount['img']  = !empty($mount['img'])?$mount['img']:'';
        $mount['type']  = !empty($mount['type'])?$mount['type']:'';

        $mount['get_way']  = !empty($mount['get_way'])?$mount['get_way']:'';
        $mount['life']  = !empty($mount['life'])?$mount['life']:'';
        $mount['speed']  = !empty($mount['speed'])?$mount['speed']:'';
        $mount['jump_height']  = !empty($mount['jump_height'])?$mount['jump_height']:'';
        $mount['price']  = !empty($mount['price'])?$mount['price']:'';
        $skill=json_decode($mount['skill'],true);
        for ($i=0;$i<3 ;$i++ ){
            $mount['skill'.($i+1).'_name']=!empty($skill[$i])?$skill[$i]['name']:'';
            $mount['skill'.($i+1).'_describe']=!empty($skill[$i])?$skill[$i]['describe']:'';
            $mount['skill'.($i+1).'_img']=!empty($skill[$i])?$skill[$i]['img']:'';
        }

        return $this->success('获取成功', $mount);
    }

    //编辑
    public function edit()
    {
//        Db::startTrans();
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $miniImg = (new MiniImg())->column('img','name');
        $row = $this->model->find($id);
        $record=(new Mini())->find($row['record_id']);
        empty($row) && $this->error('数据不存在');
        empty($record) && $this->error('数据不存在');
        $record->name = !empty($post['name'])?$post['name']:'';
        $record->second_type='坐骑';
        $record->img_url=!empty($post['img'])?$post['img']:'';

        if ($post['type']=='初阶'){
            $record->if_show=1;
        }else{
            $record->if_show=0;
        }

        $row->img = !empty($post['img'])?$post['img']:'';
        $row->type = !empty($post['type'])?$post['type']:'';
        $row->get_way = !empty($post['get_way'])?$post['get_way']:'';
        if ($post['type']=='初阶'){
            $row->p_id = 0;
        }else{
            $row->p_id=$post['chujie'];
        }
        $row->life = !empty($post['life'])?$post['life']:'';
        $row->speed = !empty($post['speed'])?$post['speed']:'';
        $row->jump_height = !empty($post['jump_height'])?$post['jump_height']:'';
        $row->price = !empty($post['price'])?$post['price']:'';

        $skill = [];
        if(!empty($post['skill1_name'])){
            $skill[]=array(
                'img'=>$post['skill1_img'],
                'name'=>$post['skill1_name'],
                'describe'=>$post['skill1_describe'],
            );
        }
        if(!empty($post['skill2_name'])) {
            $skill[] = array(
                'img' => !empty($post['skill2_img']) ? $post['skill2_img'] : '',
                'name' => !empty($post['skill2_name']) ? $post['skill2_name'] : '',
                'describe' => !empty($post['skill2_describe']) ? $post['skill2_describe'] : '',
            );
        }
        if(!empty($post['skill3_name'])) {
            $skill[] = array(
                'img' => !empty($post['skill3_img']) ? $post['skill3_img'] : '',
                'name' => !empty($post['skill3_name']) ? $post['skill3_name'] : '',
                'describe' => !empty($post['skill3_describe']) ? $post['skill3_describe'] : '',
            );
        }
        $row->skill= json_encode($skill,JSON_UNESCAPED_UNICODE);

        try {
            $save = $row->save();
            $record=$record->save();
            if ($save === false && $record === false) throw new \Exception('保存失败');
            Db::commit();
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    //删除
    public function del()
    {
        Db::startTrans();
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try{
            if ($this->model->where('record_id','in',$ids)->delete() && (new Mini())->where('id','in',$ids)->delete()) {
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                return $this->error('数据删除失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return $this->exceptionError($e);
        }
    }
}